/**
 * src/utils/index.ts
 * ------------------------------------
 * 本地数据管理工具
 * 1. DataManager：封装本地存储的 CRUD 操作，支持用户、菜品、订单、分类等数据
 * 2. 提供默认数据常量：DEFAULT_DISHES、DEFAULT_CATEGORIES、DEFAULT_USERS
 * 3. 格式化工具：formatPrice、formatDateTime 等
 * 4. 状态工具：getOrderStatusText、getOrderStatusColor 等
 * 主要用于快速体验模式，不依赖云开发环境
 * 创建日期：2025-08-06
 */
import Taro from '@tarojs/taro'
import { Dish, Order, Category, User } from '../types'

// 离线变更类型
export type OfflineChangeType = 'add' | 'update' | 'delete';

// 离线变更记录
export interface OfflineChange {
  id: string;
  collection: string;
  type: OfflineChangeType;
  data: any;
  timestamp: number;
}

// 数据管理类
export class DataManager {
  // 用户数据
  static getUser(): User | null {
    try {
      const userStr = Taro.getStorageSync('user')
      return userStr ? JSON.parse(userStr) : null
    } catch (error) {
      console.error('获取用户数据失败:', error)
      return null
    }
  }
  
  // 别名方法，为了兼容性
  static getStoredUser(): User | null {
    return this.getUser()
  }

  static saveUser(user: User): void {
    try {
      Taro.setStorageSync('user', JSON.stringify(user))
    } catch (error) {
      console.error('保存用户数据失败:', error)
    }
  }

  static removeUser(): void {
    try {
      Taro.removeStorageSync('user')
    } catch (error) {
      console.error('移除用户数据失败:', error)
    }
  }

  // 菜品数据
  static getDishes(): Dish[] {
    try {
      const dishesStr = Taro.getStorageSync('dishes')
      return dishesStr ? JSON.parse(dishesStr) : []
    } catch (error) {
      console.error('获取菜品数据失败:', error)
      return []
    }
  }

  static saveDishes(dishes: Dish[]): void {
    try {
      Taro.setStorageSync('dishes', JSON.stringify(dishes))
    } catch (error) {
      console.error('保存菜品数据失败:', error)
    }
  }

  // 订单数据
  static getOrders(): Order[] {
    try {
      const ordersStr = Taro.getStorageSync('orders')
      return ordersStr ? JSON.parse(ordersStr) : []
    } catch (error) {
      console.error('获取订单数据失败:', error)
      return []
    }
  }

  static saveOrders(orders: Order[]): void {
    try {
      Taro.setStorageSync('orders', JSON.stringify(orders))
    } catch (error) {
      console.error('保存订单数据失败:', error)
    }
  }

  // 分类数据
  static getCategories(): Category[] {
    try {
      const categoriesStr = Taro.getStorageSync('categories')
      return categoriesStr ? JSON.parse(categoriesStr) : []
    } catch (error) {
      console.error('获取分类数据失败:', error)
      return []
    }
  }

  static saveCategories(categories: Category[]): void {
    try {
      Taro.setStorageSync('categories', JSON.stringify(categories))
    } catch (error) {
      console.error('保存分类数据失败:', error)
    }
  }

  // 同步时间戳
  static getLastSyncTime(): number {
    try {
      const time = Taro.getStorageSync('lastSyncTime')
      return time ? Number(time) : 0
    } catch (error) {
      console.error('获取同步时间失败:', error)
      return 0
    }
  }

  static saveLastSyncTime(timestamp: number): void {
    try {
      Taro.setStorageSync('lastSyncTime', timestamp.toString())
    } catch (error) {
      console.error('保存同步时间失败:', error)
    }
  }

  // 离线变更管理
  static getOfflineChanges(): OfflineChange[] {
    try {
      const changesStr = Taro.getStorageSync('offlineChanges')
      return changesStr ? JSON.parse(changesStr) : []
    } catch (error) {
      console.error('获取离线变更失败:', error)
      return []
    }
  }

  static saveOfflineChange(change: OfflineChange): void {
    try {
      const changes = this.getOfflineChanges()
      changes.push(change)
      Taro.setStorageSync('offlineChanges', JSON.stringify(changes))
    } catch (error) {
      console.error('保存离线变更失败:', error)
    }
  }

  static clearOfflineChanges(): void {
    try {
      Taro.setStorageSync('offlineChanges', JSON.stringify([]))
    } catch (error) {
      console.error('清除离线变更失败:', error)
    }
  }

  static hasOfflineChanges(): boolean {
    return this.getOfflineChanges().length > 0
  }
}

// 导出工具函数
export const dataUtils = {
  saveDishes: DataManager.saveDishes,
  getDishes: DataManager.getDishes,
  saveOrders: DataManager.saveOrders,
  getOrders: DataManager.getOrders,
  saveUsers: DataManager.saveUser, // Changed to saveUser
  getUsers: DataManager.getUser, // Changed to getUser
  saveCategories: DataManager.saveCategories,
  getCategories: DataManager.getCategories,
  recordOfflineChange: DataManager.saveOfflineChange, // Changed to saveOfflineChange
  getOfflineChanges: DataManager.getOfflineChanges,
  clearOfflineChanges: DataManager.clearOfflineChanges,
  saveLastSyncTime: DataManager.saveLastSyncTime,
  getLastSyncTime: DataManager.getLastSyncTime,
  addOfflineDish: (dish: Dish) => DataManager.saveDishes([dish]), // New method
  updateOfflineDish: (dish: Dish) => DataManager.saveDishes([dish]), // New method
  deleteOfflineDish: (dishId: string) => { // New method
    const dishes = DataManager.getDishes();
    const filteredDishes = dishes.filter(d => d.id !== dishId);
    DataManager.saveDishes(filteredDishes);
  },
  addOfflineOrder: (order: Order) => DataManager.saveOrders([order]), // New method
  updateOfflineOrder: (order: Order) => DataManager.saveOrders([order]), // New method
  hasOfflineChanges: DataManager.hasOfflineChanges,
  clearAllData: () => Taro.clearStorageSync() // Changed to clearStorageSync
}

// 格式化价格
export function formatPrice(price: number): string {
  return `¥${price.toFixed(2)}`;
}

// 默认示例数据
export const DEFAULT_DISHES = [
  {
    id: 'dish-001',
    name: '宫保鸡丁',
    description: '经典川菜，鸡肉嫩滑，花生香脆',
    price: 28,
    category: '热菜',
    image: '',
    available: true,
    createdBy: 'chef',
    createdAt: new Date(),
    updatedAt: new Date()
  },
  {
    id: 'dish-002',
    name: '麻婆豆腐',
    description: '麻辣鲜香，豆腐嫩滑',
    price: 18,
    category: '热菜',
    image: '',
    available: true,
    createdBy: 'chef',
    createdAt: new Date(),
    updatedAt: new Date()
  },
  {
    id: 'dish-003',
    name: '凉拌黄瓜',
    description: '清爽可口，开胃小菜',
    price: 8,
    category: '凉菜',
    image: '',
    available: true,
    createdBy: 'chef',
    createdAt: new Date(),
    updatedAt: new Date()
  },
  {
    id: 'dish-004',
    name: '番茄蛋汤',
    description: '营养丰富的家常汤品',
    price: 12,
    category: '汤品',
    image: '',
    available: true,
    createdBy: 'chef',
    createdAt: new Date(),
    updatedAt: new Date()
  },
  {
    id: 'dish-005',
    name: '白米饭',
    description: '香软可口的白米饭',
    price: 3,
    category: '主食',
    image: '',
    available: true,
    createdBy: 'chef',
    createdAt: new Date(),
    updatedAt: new Date()
  }
];

export const DEFAULT_CATEGORIES = [
  { id: 'cat-001', name: '热菜', description: '各种热炒菜品' },
  { id: 'cat-002', name: '凉菜', description: '清爽凉菜' },
  { id: 'cat-003', name: '汤品', description: '营养汤品' },
  { id: 'cat-004', name: '主食', description: '米饭面食' },
  { id: 'cat-005', name: '饮品', description: '各种饮品' }
];

export const DEFAULT_USERS = [
  {
    id: 'chef-001',
    name: '张厨师',
    role: 'chef' as const,
    points: 100,
    avatar: '',
    createdAt: new Date(),
    updatedAt: new Date()
  },
  {
    id: 'guest-001',
    name: '李客人',
    role: 'guest' as const,
    points: 50,
    avatar: '',
    createdAt: new Date(),
    updatedAt: new Date()
  }
];

// 格式化日期时间（微信小程序兼容）
export function formatDateTime(date: Date | string | number): string {
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hour = String(d.getHours()).padStart(2, '0')
  const minute = String(d.getMinutes()).padStart(2, '0')
  const second = String(d.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`
}

// 格式化日期（微信小程序兼容）
export function formatDate(date: Date | string | number): string {
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  
  return `${year}-${month}-${day}`
}

// 格式化时间（微信小程序兼容）
export function formatTime(date: Date | string | number): string {
  const d = new Date(date)
  const hour = String(d.getHours()).padStart(2, '0')
  const minute = String(d.getMinutes()).padStart(2, '0')
  
  return `${hour}:${minute}`
}

// 计算购物车总价
export function calculateCartTotal(cartItems: any[]): number {
  return cartItems.reduce((total, item) => total + item.totalPrice, 0);
}

// 计算订单总价
export function calculateOrderTotal(items: any[]): number {
  return items.reduce((total, item) => total + item.totalPrice, 0);
}

// 获取订单状态文本
export function getOrderStatusText(status: string): string {
  const statusMap = {
    pending: '待确认',
    confirmed: '已确认',
    completed: '已完成',
    cancelled: '已取消'
  };
  return statusMap[status as keyof typeof statusMap] || status;
}

// 获取订单状态颜色
export function getOrderStatusColor(status: string): string {
  const colorMap = {
    pending: '#ff9500',
    confirmed: '#007aff',
    completed: '#34c759',
    cancelled: '#ff3b30'
  };
  return colorMap[status as keyof typeof colorMap] || '#8e8e93';
}

// 生成唯一ID
export function generateId(): string {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
}

// 初始化示例数据
export function initializeSampleData() {
  // 检查是否已经初始化
  if (Taro.getStorageSync('initialized')) {
    return;
  }

  // 创建示例用户
  const sampleUsers: User[] = [
    {
      id: 'chef-001',
      name: '主厨',
      role: 'chef',
      points: 1000,
      createdAt: new Date()
    },
    {
      id: 'guest-001',
      name: '客人1',
      role: 'guest',
      points: 100,
      createdAt: new Date()
    },
    {
      id: 'guest-002',
      name: '客人2',
      role: 'guest',
      points: 50,
      createdAt: new Date()
    }
  ];

  // 创建示例菜品
  const sampleDishes: Dish[] = [
    {
      id: 'dish-001',
      name: '宫保鸡丁',
      description: '经典川菜，鸡肉嫩滑，花生香脆',
      price: 28.00,
      category: '1',
      image: '/assets/images/dishes/kungpao-chicken.jpg',
      available: true,
      createdBy: 'chef-001',
      createdAt: new Date(),
      updatedAt: new Date()
    },
    {
      id: 'dish-002',
      name: '麻婆豆腐',
      description: '麻辣鲜香，豆腐嫩滑',
      price: 18.00,
      category: '1',
      image: '/assets/images/dishes/mapo-tofu.jpg',
      available: true,
      createdBy: 'chef-001',
      createdAt: new Date(),
      updatedAt: new Date()
    },
    {
      id: 'dish-003',
      name: '凉拌黄瓜',
      description: '清爽可口，开胃小菜',
      price: 8.00,
      category: '2',
      image: '/assets/images/dishes/cucumber-salad.jpg',
      available: true,
      createdBy: 'chef-001',
      createdAt: new Date(),
      updatedAt: new Date()
    },
    {
      id: 'dish-004',
      name: '紫菜蛋花汤',
      description: '营养丰富，味道鲜美',
      price: 12.00,
      category: '3',
      image: '/assets/images/dishes/seaweed-soup.jpg',
      available: true,
      createdBy: 'chef-001',
      createdAt: new Date(),
      updatedAt: new Date()
    },
    {
      id: 'dish-005',
      name: '白米饭',
      description: '香软可口的白米饭',
      price: 2.00,
      category: '4',
      image: '/assets/images/dishes/white-rice.jpg',
      available: true,
      createdBy: 'chef-001',
      createdAt: new Date(),
      updatedAt: new Date()
    },
    {
      id: 'dish-006',
      name: '可乐',
      description: '冰镇可乐，清爽解腻',
      price: 5.00,
      category: '5',
      image: '/assets/images/dishes/cola.jpg',
      available: true,
      createdBy: 'chef-001',
      createdAt: new Date(),
      updatedAt: new Date()
    },
    {
      id: 'dish-007',
      name: '红烧肉',
      description: '肥而不腻，入口即化',
      price: 32.00,
      category: '1',
      image: '/assets/images/dishes/hongshao-pork.jpg',
      available: true,
      createdBy: 'chef-001',
      createdAt: new Date(),
      updatedAt: new Date()
    },
    {
      id: 'dish-008',
      name: '蒜蓉西兰花',
      description: '清淡爽口，营养丰富',
      price: 15.00,
      category: '1',
      image: '/assets/images/dishes/broccoli.jpg',
      available: true,
      createdBy: 'chef-001',
      createdAt: new Date(),
      updatedAt: new Date()
    }
  ];

  // 保存示例数据
  sampleUsers.forEach(user => DataManager.saveUser(user));
  DataManager.saveDishes(sampleDishes);
  Taro.setStorageSync('initialized', true);
} 